<template>
  <div>
    <q-layout>
      <q-layout-header ref="header">
        <xheader :title="title" :show-back="false"></xheader>
      </q-layout-header>
      <q-page-container>
        <xscrollarea :scroll-height="scrollHeight">
          <q-page padding>
            <transition-group appear
                              enter-active-class="animated fadeIn"
            >
              <div v-show="mainTabbarType === 'main'" key="main">
                <q-list separator>
                  <q-collapsible v-for="m in mainMenus"
                                 :key="m.id"
                                 :avatar="$conf.server +'/'+ m.iconPath"
                                 v-if="(m.parentId === '0' || m.parentId === null) && (m.menuType !== 'REPORT')"
                                 :label="m.name"
                                 opened>
                    <template slot="header">
                      <q-item-side>
                        <div class="menucolsicon">
                          <img :src="$conf.server +'/'+ m.iconPath">
                        </div>
                      </q-item-side>
                      <q-item-main :label="m.name"/>

                    </template>
                    <div class="row">
                      <div class="menugrid" v-ripple
                           v-for="mm in mainMenus"
                           :key="mm.id"
                           v-if="mm.parentId === m.id"
                           @click="toPage(mm.url,mm.name)">
                        <div class="menugridicon">
                          <img :src="$conf.server +'/'+ mm.iconPath">
                        </div>
                        <div class="menugridlabel">
                          {{mm.name}}
                        </div>
                      </div>
                    </div>
                  </q-collapsible>

                </q-list>
              </div>
              <div v-show="mainTabbarType === 'statistics'" key="statistics">


                <q-list separator>
                  <q-collapsible v-for="m in mainMenus"
                                 :key="m.id"
                                 :avatar="$conf.server +'/'+ m.iconPath"
                                 v-if="(m.parentId === '0' || m.parentId === null) && (m.menuType === 'REPORT')"
                                 :label="m.name"
                                 opened>
                    <template slot="header">
                      <q-item-side>
                        <div class="menucolsicon">
                          <img :src="$conf.server +'/'+ m.iconPath">
                        </div>
                      </q-item-side>
                      <q-item-main :label="m.name"/>

                    </template>
                    <div class="row">
                      <div class="menugrid" v-ripple
                           v-for="mm in mainMenus"
                           :key="mm.id"
                           v-if="mm.parentId === m.id"
                           @click="toPage(mm.url,mm.name)">
                        <div class="menugridicon">
                          <img :src="$conf.server +'/'+ mm.iconPath">
                        </div>
                        <div class="menugridlabel">
                          {{mm.name}}
                        </div>
                      </div>
                    </div>
                  </q-collapsible>

                </q-list>

              </div>
              <div v-show="mainTabbarType === 'user'" key="user">
                <q-card inline class="full-width">
                  <q-item>
                    <q-item-side :avatar="userPng"/>
                    <q-item-main>
                      <q-item-tile label>{{userName}}</q-item-tile>
                      <!--<q-item-tile sublabel>Subhead</q-item-tile>-->
                    </q-item-main>
                  </q-item>
                  <!--<q-card-media>-->
                  <!--<img src="statics/parallax2.jpg">-->
                  <!--</q-card-media>-->
                  <q-card-title>
                    用户名：{{userCode}}

                  </q-card-title>
                  <q-item>
                    <div class="row">
                      <div class="col"><p>组织：{{user.orgName}}</p></div>
                    </div>

                  </q-item>
                  <q-item>
                    <div class="row">
                      <div class="col"><p>机构：{{user.clientName}}</p></div>
                    </div>
                  </q-item>
                  <q-card-actions>
                    <div style="width:100%;text-align: right">
                      <q-btn flat @click="resetPassword">修改密码</q-btn>
                      <q-btn flat @click="editInfo">修改资料</q-btn>
                    </div>
                  </q-card-actions>
                </q-card>
                <br> <br>
                <q-btn label="退出" color="red" class="full-width" @click="loginOut"/>
              </div>
              <div v-show="mainTabbarType === 'settings'" key="settings">
                <q-card inline class="full-width">
                  <q-card-media>
                    <img src="../assets/l_logo.png">
                  </q-card-media>
                  <q-item>
                    <q-item-main>
                      <q-item-tile label>力控元海{{appType}}系统-APP</q-item-tile>
                      <!--<q-item-tile sublabel>Subhead</q-item-tile>-->
                    </q-item-main>
                  </q-item>
                  <q-card-main>
                    力控元海以信息化促进自动化，为工厂用户提供管控一体化解决之道，勇当工业IT的先锋，为用户提供具有国际竞争力的工业自动化软件产品和服务。
                  </q-card-main>
                  <!--<q-card-media>-->
                  <!--<img src="statics/parallax2.jpg">-->
                  <!--</q-card-media>-->
                  <q-card-title>

                    <q-icon name="phone"/>&nbsp;&nbsp;
                    <a href="tel:400-859-8181">400-859-8181</a>
                    <span slot="subtitle">智能制造事业部
                    <br>
                    地址：湖南省长沙市高新区文轩路27号麓谷企业广场C4栋501
                    <br>
                      邮箱：caop@sunwayland.com.cn <br>
                     版本：{{$conf.version}}<br></span>
                  </q-card-title>
                  <q-card-actions>

                    <div style="width:100%;text-align: right">
                      <q-btn @click="showContactUs = true">微信公众号</q-btn>
                    </div>
                  </q-card-actions>
                </q-card>

              </div>
            </transition-group>
          </q-page>
        </xscrollarea>
      </q-page-container>

      <q-layout-footer>
        <q-tabs position="bottom" :value="mainTabbarType" ref="tab" align="justify">
          <!-- 选项卡 - 注意slot="title" -->
          <q-tab slot="title" label="主页" name="main" icon="home" @select="showBoard('main')"/>
          <q-tab slot="title" label="统计" name="statistics" icon="dashboard" @select="showBoard('statistics')"/>
          <q-tab slot="title" label="用户" name="user" icon="person" @select="showBoard('user')"/>
          <q-tab slot="title" label="设置" name="settings" icon="settings" @select="showBoard('settings')"/>
        </q-tabs>
      </q-layout-footer>
    </q-layout>
    <q-modal v-model="showContactUs" minimized>
      <div class="row">
        <q-btn class="full-width" flat round dense>长按保存</q-btn>
      </div>
      <div class="row">
        <img v-touch-hold="showSave" src="../assets/us.png"/>
      </div>
      <div class="row">
        <div style="width:100%;text-align: right">
          <q-btn @click="showContactUs = false" class="full-width" icon="close" color="primary">知道了</q-btn>
        </div>
      </div>
    </q-modal>

  </div>
</template>

<script>
  import utils from '../js/utils'
  import '../js/url'
  import MT from '../js/mutation-types'
  import { mapState } from 'vuex'
  import Xheader from '../components/xheader'
  import Xscrollarea from '../components/xscrollarea'
  import userPng from '../assets/user.png'

  export default {
    name: 'index',
    components: { Xscrollarea, Xheader },
    computed: {
      ...mapState({
        mainMenus: state => state.mainMenus,
        userCode: state => state.userCode,
        userName: state => state.userName,
        user: state => state.user,
        mainSelected: state => state.mainSelected,
        mainSelectedName: state => state.mainSelectedName,
        statisticsSelected: state => state.statisticsSelected,
        statisticsSelectedName: state => state.statisticsSelectedName,
        mainTabbarType: state => state.mainTabbarType,
        appType: state => {
          if (state.appType) {
            return state.appType.toUpperCase()
          } else {
            return 'MES'
          }
        },
      })

    },
    data: () => ({
      title: '力控元海MES系统',
      utils: utils,
      searchText: '',
      searchResults: [],
      showSearch: false,
      userPng: userPng,
      scrollHeight: 0,
      showContactUs: false
    }),
    mounted () {
      this.scrollHeight = this.$parent.webHeight - this.$refs.header.$el.clientHeight - this.$refs.tab.$el.clientHeight
    },
    methods: {
      initMenu () {
        if (!this.mainMenus) {
          this.axios.get(this.$conf.server + '/loginAction/getMenus.html', {
            params: {
              userCode: this.userCode
            }
          }).then(res => {
              if (res.data.data) {
                this.$store.commit(MT.SET_MAIN_MENUS, res.data.data)
                this.menusToRoutes(res.data.data)
                this.menusReady()
              } else {
                this.$router.replace('login')
              }
            }
          )
        } else {
          this.menusReady()
        }
      },
      menusToRoutes (menus) {
        let rs = []
        let names = new Set()
        for (let m of menus) {
          if (m.url) {
            let name = utils.urlToRoute(m.url)
            if (!names.has(name) && name !== 'index' && name !== 'login') {
              names.add(name)
              let path = new Url(m.url).path
              rs.push({
                path: '/' + path,
                name: name,
                component: () => import('./mes/' + name + '.vue'),
                props: route => route.query
              })
            }
          }
        }
        this.$router.addRoutes(rs)
      },
      backMenu () {

      },
      showBoard (type) {
        this.$store.commit(MT.SET_MAIN_TABBAR_TYPE, type)
      },
      setMainSelected (id, name) {
        this.$store.commit(MT.SET_MAIN_SELECTED, { id: id, name: name })
      },
      setStatisticsSelected (id, name) {
        this.$store.commit(MT.SET_STATISTICS_SELECTED, { id: id, name: name })
      },
      initTabbar () {
      },
      loginOut () {
        this.axios.post(this.$conf.server + '/loginAction/loginOut.html')
        this.$store.commit(MT.CLEAR_STATE)
        this.notRememberMe()
        // this.$router.push('login')
        window.location.href = process.env.BASE_URL
      },
      initUser () {
        if (this.userName === undefined && this.userCode) {
          this.axios.get(this.$conf.server + '/loginAction/getUserInfo.html', {
            params: {
              userCode: this.userCode
            }
          }).then(res => {
            if (res.data.status === 'ok') {
              this.$store.commit(MT.SET_USER_NAME, res.data.msg)
              this.$store.commit(MT.SET_USER, res.data.data)
            }
          })
        }
      },
      notRememberMe () {
        let localStorage = window.localStorage
        if (localStorage) {
          localStorage.removeItem('userCode')
          localStorage.removeItem('password')
        }
        try {
          window.pda.notRememberMe()
        } catch (e) {
        }
      },
      menusReady () {
        this.redirect()
      },
      redirect () {
        if (this.$route.params && this.$route.params.redirect) {
          // this.$router.push({ name: this.$route.params.redirect, query: this.$route.query })
        }
      },
      toPage (url, name) {
        this.$router.push({ path: '/' + utils.urlTrans(url), query: { title: name } })
      },
      resetPassword () {
        this.$parent.info('当前系统不支持APP段修改密码，请登录WEB管理台')
      },
      editInfo () {
        this.$parent.info('当前系统不支持APP段修改信息，请登录WEB管理台')
      },
      initOrg () {
        if (this.user.orgName === undefined && this.userCode) {
          this.axios.get(this.$conf.server + '/loginAction/getOrgClentName.html', {
            params: {
              userCode: this.userCode
            }
          }).then(res => {
            if (res.data.result) {
              let user = this.user
              user.orgName = res.data.data.orgnames
              user.clientName = res.data.data.clnames
              this.$store.commit(MT.SET_USER, user)
            }
          })
        }
      },
      showSave () {
        this.$q.actionSheet({
          title: '',
          actions: [
            {
              label: '保存图片',
              // 可选的
              color: 'negative',
              // 选择以下两项之一：
              icon: 'save_alt', // 如果您仅想使用图标，则指定
              // 并从“action”参数中识别操作
              handler () {
                try {
                  // 安卓交互
                  window.pda.saveImage()
                } catch (e) {
                }
                // _this.$parent.info('请截屏或长按图片保存')
              }
            }
          ]
        })
      },
      initTitle () {
        if (this.appType) {
          this.title = `力控元海${this.appType.toUpperCase()}系统`
        }
      }
    },
    created () {
      // this.menusToRoutes(this.menus)
      this.initTitle()
      this.initTabbar()
      this.initMenu()
      this.initUser()
      this.initOrg()
    }
  }
</script>

<style>
  .menugrid {
    width: 33.33333333%;
    position: relative;
    float: left;
    padding: 20px 10px;
    box-sizing: border-box
  }

  .menugridicon {
    width: 38px;
    height: 38px;
    margin: 0 auto
  }

  .menugridicon img {
    width: 100%;
    height: 100%
  }

  .menucolsicon {
    width: 25px;
    height: 25px;
    margin: 0 auto
  }

  .menucolsicon img {
    width: 100%;
    height: 100%
  }

  .menugridlabel {
    font-size: 14px;
    text-align: center;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden
  }
</style>
